const express = require('express')
const http = require('http')
const cors = require('cors')
const socketIo = require('socket.io')

const healthRouter = require('./routes/health')
const studentsRouter = require('./routes/students')
const sessionsRouter = require('./routes/sessions')
const permissionsRouter = require('./routes/permissions')

// 创建 Express 应用
const app = express()

// 创建 http 服务器
const server = http.createServer(app)

// 解决跨域问题
app.use(cors())

// 请求数据处理
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 路由
app.use('/api/v1/health', healthRouter)
app.use('/api/v1/students', studentsRouter)
app.use('/api/v1/sessions', sessionsRouter)
app.use('/api/v1/permissions', permissionsRouter)

// 监听
server.listen(3000, () => console.log('server running at http://localhost:3000'))

// socket.io
// 模拟向客户端发消息
let id = 1
const list = []
const io = socketIo(server, { cors: true })
io.on('connection', socket => {
  console.log('用户连接...')
  socket.emit('message', { list })
  socket.on('disconnect', () => {
    console.log('用户断开连接...')
    // 释放资源
    // TODO...
  })
})
const random = (min, max) => Math.floor(Math.random() * (max - min)) + min
const genData = () => {
  list.push({id, time: Date.now(), title: '标题' + (id++)})
  io.emit('message', {
    list
  })
  setTimeout(genData, random(5, 15) * 1000)
}

genData()
